package com.lbb.waimai.controller;

import com.lbb.waimai.entiry.ShoppingCart;
import com.lbb.waimai.entiry.vo.ShoppingCartVo;
import com.lbb.waimai.result.R;
import com.lbb.waimai.service.ShoppingCartService;
import com.lbb.waimai.utils.JwtHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@CrossOrigin
@RequestMapping("shopping")
@RestController
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    //加入购物车，要判断是要更新数量还是新增
    @PostMapping("/takeInCart")
    public R takeInCart(@RequestBody ShoppingCartVo shoppingCartVo, HttpServletRequest request) {
        Long id = JwtHelper.getUserId(request);
        Integer userId = Integer.valueOf(id.toString());
        shoppingCartService.takeInCart(shoppingCartVo,userId);
        return R.ok().message("已加入购物车");
    }

    //获取购物车的内容,根据userid以及status为0（未生成订单，未支付）状态下的购物车
    @GetMapping("/findInCart")
    public R findInCart(HttpServletRequest request) {
        Long userId = JwtHelper.getUserId(request);
        List<ShoppingCart> cartList = shoppingCartService.findInCart(userId);
//        //封装购物车
//        List<ShoppingCartVo> shoppingCartVos = new ArrayList<>();
//        for (ShoppingCart cart : cartList) {
//            ShoppingCartVo shoppingCartVo = new ShoppingCartVo();
//
//            shoppingCartVo.setId(cart.getId());
//            shoppingCartVo.setCount(cart.getFCount());
//            shoppingCartVo.setName(cart.getFName());
//            shoppingCartVo.setPrice(cart.getFPrice());
//            shoppingCartVo.setSum(cart.getFSum());
//            shoppingCartVos.add(shoppingCartVo);
//        }
        return R.ok().data("data", cartList);
    }

    //清空购物车
    @DeleteMapping("/clearCart")
    public R clearCart(HttpServletRequest request) {
        Long id = JwtHelper.getUserId(request);
        Integer userId = Integer.valueOf(id.toString());
        shoppingCartService.clearCart(userId);
        return R.ok();
    }

    //从购物车中删除一个菜品,根据菜品id
    @DeleteMapping("/deleteFood")
    public R deleteFood(Integer id, HttpServletRequest request) {
        Integer userId = Integer.valueOf(JwtHelper.getUserId(request).toString());
        shoppingCartService.deleteFood(id, userId);
        return R.ok();
    }

}
